<template>
  <div class="page-container">
    <h2>图文课程管理</h2>
    
    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="课程信息">
        <el-input v-model="searchForm.photoInfo" placeholder="请输入课程信息" clearable />
      </el-form-item>
      <el-form-item label="价格范围">
        <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价格" />
        <span style="margin: 0 10px">-</span>
        <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价格" />
      </el-form-item>
      <el-form-item label="课程状态">
        <el-select v-model="searchForm.photoState" placeholder="请选择课程状态" clearable>
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增课程
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table 
      :data="displayedData" 
      v-loading="loading"
      class="table-container"
      border
      stripe
    >
      <template #empty>
        <div style="padding: 24px; color: #909399;">暂无数据</div>
      </template>
      <el-table-column prop="photoId" label="课程ID" width="80" />
      <el-table-column prop="photoInfo" label="课程信息" min-width="200" />
      <el-table-column prop="photoPrice" label="课程价格" width="120">
        <template #default="{ row }">
          <span style="color: #f56c6c; font-weight: bold;">
            ¥{{ row.photoPrice?.toFixed(2) || '0.00' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="subscribeNum" label="订阅数" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ row.subscribeNum || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="photoState" label="课程状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.photoState === 1 ? 'success' : 'danger'">
            {{ row.photoState === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5,10,20,50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="课程信息" prop="photoInfo">
          <el-input 
            v-model="formData.photoInfo" 
            type="textarea"
            :rows="3"
            placeholder="请输入课程详细信息" 
          />
        </el-form-item>
        <el-form-item label="课程价格" prop="photoPrice">
          <el-input-number 
            v-model="formData.photoPrice" 
            :min="0" 
            :precision="2"
            placeholder="请输入课程价格"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="订阅数" prop="subscribeNum">
          <el-input-number v-model="formData.subscribeNum" :min="0" />
        </el-form-item>
        <el-form-item label="课程状态" prop="photoState">
          <el-radio-group v-model="formData.photoState">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { photoApi } from '@/api/photo'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  photoInfo: '',
  minPrice: null,
  maxPrice: null,
  photoState: null
})

// 表格数据
const tableData = ref([])

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 过滤后的数据
const filteredData = computed(() => {
  return (tableData.value || []).filter(item => {
    const matchInfo = !searchForm.photoInfo || (item.photoInfo || '').includes(searchForm.photoInfo)
    const matchState = (searchForm.photoState === null || searchForm.photoState === undefined) || item.photoState === searchForm.photoState
    const matchMin = (searchForm.minPrice === null || searchForm.minPrice === undefined) || (Number(item.photoPrice) >= Number(searchForm.minPrice))
    const matchMax = (searchForm.maxPrice === null || searchForm.maxPrice === undefined) || (Number(item.photoPrice) <= Number(searchForm.maxPrice))
    return matchInfo && matchState && matchMin && matchMax
  })
})

// 当前页展示数据
const displayedData = computed(() => {
  pagination.total = filteredData.value.length
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 表单数据
const formData = reactive({
  photoId: null,
  photoInfo: '',
  photoPrice: 0,
  subscribeNum: 0,
  photoState: 1
})

// 表单验证规则
const formRules = {
  photoInfo: [
    { required: true, message: '请输入课程信息', trigger: 'blur' }
  ],
  photoPrice: [
    { required: true, message: '请输入课程价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  photoState: [
    { required: true, message: '请选择课程状态', trigger: 'change' }
  ]
}


// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取课程列表
const getPhotoList = async () => {
  try {
    loading.value = true
    const response = await photoApi.getPhotoList(searchForm)
    tableData.value = response.data || []
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  getPhotoList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    photoInfo: '',
    minPrice: null,
    maxPrice: null,
    photoState: null
  })
  getPhotoList()
}

// 新增课程
const handleAdd = () => {
  dialogTitle.value = '新增课程'
  resetFormData()
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除课程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await photoApi.deletePhoto(row.photoId)
    ElMessage.success('删除成功')
    getPhotoList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (formData.photoId) {
      await photoApi.updatePhoto(formData)
      ElMessage.success('修改成功')
    } else {
      await photoApi.addPhoto(formData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getPhotoList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(formData.photoId ? '修改失败' : '添加失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    photoId: null,
    photoInfo: '',
    photoPrice: 0,
    subscribeNum: 0,
    photoState: 1
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
}

// 初始化
onMounted(() => {
  getPhotoList()
})
</script>

<style scoped>
.search-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>


